import { ViteSSG, ViteSSGContext } from 'vite-ssg'
import generatedRoutes from 'virtual:generated-pages'
import { setupLayouts } from 'layouts-generated'
import { createWebHashHistory } from 'vue-router'
import App from './App.vue'
const routes = setupLayouts(generatedRoutes)

// if need import other files, change suffix below
const modules = import.meta.globEager('./modules/*.{ts,css}')

// https://github.com/antfu/vite-ssg
// noinspection JSUnusedGlobalSymbols
export const createApp = ViteSSG(
  App,
  // {routes, history: undefined} will cause 'location is undefined' error with ssr
  import.meta.env.VITE_APP_SSR ? { routes } : { routes, history: createWebHashHistory() },
  (ctx) => {
    Object.entries(modules).forEach(([k, v]: [string, any]) => {
      if (import.meta.env.DEV) console.debug(`imported module ${k}:`, v)
      share(k, registerModule(ctx, v))
    })
    function getModuleName(key: string) {
      const p2 = key.lastIndexOf('.')
      return p2 < 0 ? key.substr(10) : key.substring(10, p2) // length of './modules/' is 10
    }
    function registerModule(context: ViteSSGContext, module: Record<string, Record<string, any>>) {
      const exported = module.default
      if (typeof exported === 'function') {
        const plugin = exported(context)
        if (typeof plugin === 'function' || typeof plugin?.install === 'function') context.app.use(plugin)
        return plugin
      }
    }
    function share(key: string, module: any) {
      if (module !== undefined) window.shared[getModuleName(key)] = module
    }
  },
)
